package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
	"xiegao/caches"
	"xiegao/common"
	"xiegao/models"
)

type Login struct {
	beego.Controller
}

// @Title 登陆
// @Description 登陆
// @Success 200 {"code":200,"msg":"登陆成功","data":{"token":"jwt token"}}
// @Params username body string true 登录名
// @Params password body string true 密码
// @failure 500 {"code":500,"msg":"未找到用户"}
// @router /login [post]
func (self *Login) Post() {

	ByteBody, _ := ioutil.ReadAll(self.Ctx.Request.Body)
	defer self.Ctx.Request.Body.Close()

	body := common.DecodeJson(ByteBody)
	username := body["username"]
	password := body["password"]
	o := orm.NewOrm()
	queryuser := o.QueryTable("user")
	var user models.User
	error := queryuser.Filter("username__exact", username).One(&user)
	if error != nil {
		self.Data["json"] = map[string]interface{}{"code": 403, "msg": "登陆失败"}
		self.ServeJSON()
		self.StopRun()
	}
	res := user.CheckPassword(password.(string))
	if res {
		jwtStr := user.Jwt()
		self.Data["json"] = map[string]interface{}{"code": 200, "msg": "登陆成功", "data": map[string]interface{}{"token": jwtStr}}
		self.ServeJSON()
		self.StopRun()
	}
	self.Data["json"] = map[string]interface{}{"code": 403, "msg": "登陆失败"}
	self.ServeJSON()
	self.StopRun()
}

// @Title 微信授权登陆
// @Description 登陆
// @Success 200 {"code":200,"data":{"token":"jwt"},"msg":"登陆成功"}
// @router /login/code [get]
func (self *Login) LoginByWechatCode(){
	code := self.Input().Get("code")
	fmt.Println(code)
	Auth := caches.CreateAuthSession()
	user := Auth.GetUser(code)
	self.Data["json"] = map[string]interface{}{
		"code":200,
		"msg":"获取成功",
		"data":map[string]interface{}{
			"token":user.Jwt(),
		},
	}
	self.ServeJSON()
}

// @Title 微信openid登陆
// @Description 登陆
// @Success 200 {"code":200,"data":{"token":"jwt"},"msg":"登陆成功"}
// @router /login/openid [get]
func (self *Login) LoginByOpenid(){
	openid := self.Ctx.Input.Param("openid")
	user := &models.WeiXinUser{}
	o := orm.NewOrm()
	error := o.QueryTable("wei_xin_user").Filter("openid",openid).One(user)
	if error != nil{
		self.Data["json"] = map[string]interface{}{
			"code":404,
			"msg":"找不到用户",
		}
		self.ServeJSON()
		self.StopRun()
	}
	self.Data["json"] = map[string]interface{}{
		"code":200,
		"msg":"获取成功",
		"data":map[string]interface{}{
			"token":user.Jwt(),
		},
	}
	self.ServeJSON()
}